<template>
  <view class="page">
    <u-navbar @leftClick="navLeftClick" :fixed="false" title="开通VIP会员" placeholder bgColor="#fff"></u-navbar>
    <image class="banner" src="../../static/activateMembership.png" />

    <view v-if="userInfo.isVip == '1'" class="u-m-b-20 u-text-center u-font-36">VIP到期时间:<text style="font-weight: bold;">{{ userInfo.vipExpiresTime }}</text></view>
    <view class="btn" :style="'background-image: url('+btn+');'">
      <view class="u-flex-1 view" style="color: #FCDDBA;line-height: 100rpx;" @click="showActivationCode=true">激活码兑换VIP会员</view>
      <view class="u-flex-1 view" style="color: #FFFFFF;font-weight: 500;" @click="showPayType=true">
        <template v-if="userInfo.isVip == '1'">
          <view><text class="u-font-40">续费</text>开通VIP会员</view>
        </template>
        <template v-else>
          <view><text class="u-font-40">99</text>元开通VIP会员</view>
          <view style="font-weight: 400;font-size: 20rpx;color: #8F7D6D;text-decoration-line: line-through;">原价：¥998.00</view>
        </template>
      </view>
    </view>
    <view class="u-text-center u-m-b-24" v-if="hotProductsList.length">
      <image style="width: 149.62rpx;height: 40rpx;" src="../../static/hot.png" />
    </view>
    <view class="goods-list">
      <view class="goods-item" v-for="item in hotProductsList" :key="item.id" @click="jumpTo('/pages/goodsDetail/goodsDetail?id='+item.id)">
        <image style="width: 344rpx;height: 344rpx;flex-shrink: 0;" :src="item.subtitle?item.subtitle.split(',')[0]:''" mode="aspectFill" />
        <view class="name u-line-2">{{ item.title }}</view>
        <view class="u-flex u-row-between u-p-l-12 u-p-r-12 u-p-b-22">
          <view class="price"><text>¥</text> {{ (item.price / 100).toFixed(2) }}</view>
          <view class="num">仅剩{{ item.stock }}件</view>
        </view>
      </view>
    </view>
    <u-popup :show="showActivationCode" :round="20" mode="center" closeable @close="closeCard">
      <view class="activation-code customize-popup">
        <view class="popup-title">激活码开通VIP会员</view>
        <view class="popup-input">
          <u--input
            placeholder="请输入卡号"
            border="surround"
            v-model="cardNo"
          ></u--input>
        </view>
        <view class="popup-input">
          <u--input
            placeholder="请输入激活码"
            border="surround"
            v-model="cardSecret"
          ></u--input>
        </view>
        <!-- <view class="popup-tips">*该激活码已被激活</view> -->
        <view class="btn-list">
          <view class="btn-item" style="color: #56CB03;background-color: #fff;" @click="closeCard">取消</view>
          <view class="btn-item" style="color: #fff;background-color: #56CB03;" @click="submitCard">确定</view>
        </view>
      </view>
		</u-popup>
    <payTypePopup :closePopup="() => showPayType=false" :showPayType="showPayType" :pay="pay" />
  </view>
</template>

<script>
import payTypePopup from '../../components/payTypePopup.vue'
import btn from '../../static/membershipBtn.png'
import { gethotProductsList, openMember, getUserInfo, aLiPay, wxPay, wxMiniAppPay, paidMember } from '@/api/index'
import { isWeChatBrowser, utilWxLogin } from "@/common/util";
const vipMoney = 99 * 100

export default {
  components: {
    payTypePopup,
  },
  data() {
    return {
      btn,
      showActivationCode: false,
      showPayType: false,
      cardNo: '',
      cardSecret: '',
      hotProductsList: [],
      userInfo: {},
    };
  },
  async onLoad() {
    await utilWxLogin()
    this.gethotProducts()
  },
  onShow() {
    uni.showLoading()
    getUserInfo({}).then(res => {
      uni.hideLoading()
      uni.setStorageSync('userInfo', {...res.user, roles: res.roles})
      this.userInfo = {...res.user, roles: res.roles}
    })
  },
  methods: {
    closeCard() {
      this.cardNo = ''
      this.cardSecret = ''
      this.showActivationCode = false
    },
    submitCard() {
      const that = this
      if(!this.userInfo.openId) {
        uni.showToast({
          icon: 'none',
          title: `请先绑定微信`
        })
        setTimeout(() => {
          that.jumpTo('/pages/userInfo/userInfo')
        }, 1000)
        return
      } else if(!this.userInfo.phonenumber) {
        uni.showToast({
          icon: 'none',
          title: `请先绑定手机号`
        })
        setTimeout(() => {
          that.jumpTo('/pages/userInfo/userPhone')
        }, 1000)
        return
      }
      if(this.cardNo === '' || this.cardSecret === '') {
        uni.showToast({
          icon: 'none',
          title: `请输入卡号或激活码`
        })
        return
      }
      openMember({ cardNo: this.cardNo, cardSecret: this.cardSecret }).then(res => {
        uni.showToast({
          icon: 'none',
          title: `激活成功`
        })
        this.closeCard()
        getUserInfo({}).then(res => {
          uni.setStorageSync('userInfo', {...res.user, roles: res.roles})
          this.userInfo = {...res.user, roles: res.roles}
        })
      })
    },
    // 热销榜单
    async gethotProducts() {
      uni.showLoading({ mask: true })
      await gethotProductsList({quantity: 20, categoryType: 0, deptId: uni.getStorageSync('userInfo').deptId || 100}).then(res => {
        uni.hideLoading()
        this.hotProductsList = res.data
      })
    },
    pay(e) {
      const that = this
      if(!this.userInfo.openId) {
        uni.showToast({
          icon: 'none',
          title: `请先绑定微信`
        })
        setTimeout(() => {
          that.jumpTo('/pages/userInfo/userInfo')
        }, 1000)
        return
      } else if(!this.userInfo.phonenumber) {
        uni.showToast({
          icon: 'none',
          title: `请先绑定手机号`
        })
        this.showPayType = false
        setTimeout(() => {
          that.jumpTo('/pages/userInfo/userPhone')
        }, 1000)
        return
      }
      this.showPayType = false
      if(e == 'ali') {
        const payUrl = `${window.location.origin}/pages/aliPay/aliPay?totalAmount=${vipMoney / 100}&payType=1&subject=开通会员&deptId=${uni.getStorageSync('userInfo').deptId}&userId=${uni.getStorageSync('userInfo').userId}&userName=${uni.getStorageSync('userInfo').userName}&phonenumber=${uni.getStorageSync('userInfo').phonenumber}`
        uni.setClipboardData({
          data: payUrl,
          success: function () {
            uni.showModal({
              title: '提示',
              content: '复制成功,请使用系统浏览器支付.',
              showCancel: false,
              success: function (res) {
                
              }
            });
          },
        });
        // const parameter = {
        //   totalAmount: vipMoney / 100,
        //   payType: '1',
        //   subject: '开通会员',
        //   deptId: uni.getStorageSync('userInfo').deptId,
        // }
        // aLiPay(parameter).then(res => {
        //   document.write(res.msg)
        // })
      } else if(e == 'wechat') {
        // 判断是否是微信浏览器
        if (isWeChatBrowser()) {
          uni.showLoading({ mask: true })
          wxMiniAppPay({ openId: uni.getStorageSync('userInfo').openId, payType: '1', totalAmount: vipMoney}).then((res) => {
            uni.hideLoading()
            const data = JSON.parse(res.data.payParams)
            const userId = res.data.userId
            const orderNo = res.data.outTradeNo
            const { appId, nonceStr, paySign, signType, timeStamp } = data
            
            let payParams = {
              appId: appId,
              timeStamp: timeStamp,
              nonceStr: nonceStr,
              package: data.package,
              signType: signType,
              paySign: paySign,
            }
            WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, (res) => {
              if (res.err_msg === 'get_brand_wcpay_request:ok') {
                paidMember({
                  orderNo,
                  orderAmount: vipMoney,
                  userId,
                }).then(() => {
                  uni.showToast({
                    icon: 'none',
                    title: `支付成功`
                  })
                  getUserInfo({}).then(res => {
                    uni.setStorageSync('userInfo', {...res.user, roles: res.roles})
                    that.userInfo = {...res.user, roles: res.roles}
                  })
                })
              } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
                uni.showToast({
                  icon: 'none',
                  title: `取消支付`
                })
              } else {
                uni.showToast({
                  icon: 'none',
                  title: `支付失败`
                })
              }
            })
          })
        } else {
          uni.showToast({
            icon: 'none',
            title: `h5支付暂未开通`
          })
          // wxPay({})
        }

      } 
    }
  },
};
</script>

<style lang="scss" scoped>
.page {
  width: 750rpx;
  min-height: 100vh;
  background-color: #F5F5F5;
  padding-bottom: 80rpx;
  position: relative;
  .banner {
    width: 750rpx;
    height: 412rpx;
    margin-bottom: 12rpx;
  }
  .btn {
    width: 702rpx;
    height: 100rpx;
    margin: 0 auto;
    margin-bottom: 24rpx;
    display: flex;
    font-size: 28rpx;
    background-repeat: no-repeat;
    background-size: 702rpx 100rpx;
    .view {
      height: 100rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
  }
  .goods-list {
    width: 702rpx;
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx 14rpx;
    margin: 0 auto;
    .goods-item {
      width: 344rpx;
      background: #fff;
      border-radius: 8rpx;
      .name {
        height: 88rpx;
        margin-top: 16rpx;
        margin-bottom: 14rpx;
        padding: 0 12rpx;
        font-size: 28rpx;
        color: #000000;
        line-height: 44rpx;
      }
      .price {
        font-weight: 500;
        font-size: 28rpx;
        color: #E20300;
        text {
          font-size: 24rpx;
        }
      }
      .num {
        font-size: 24rpx;
        color: #818181;
      }
    }
  }
}
.activation-code {
  width: 632rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding-top: 60rpx;
  padding: 60rpx 24rpx 28rpx;
  .popup-input {
    margin-bottom: 16rpx;
  }
  .popup-tips {
    font-size: 24rpx;
    color: rgba(226, 3, 0, 1);
    text-align: center;
    margin-bottom: 16rpx;
  }
  .btn-list {
    display: flex;
    gap: 24rpx;
    .btn-item {
      flex: 1;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 2rpx solid #56CB03;
      background-color: #FCDDBA;
      font-size: 28rpx;
      border-radius: 200rpx;
    }
  }
}
.pay-type {
  width: 750rpx;
  height: 400rpx;
  background: #FFFFFF;
  border-radius: 20rpx;
  padding: 40rpx 24rpx ;
  .pay-list {
    .pay-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 30rpx;
      margin-bottom: 34rpx;
      border-bottom: 2rpx solid #E1E1E1;
      .pay-icon {
        display: flex;
        align-items: center;
        gap: 28rpx;
        font-size: 28rpx;
        image {
          width: 60rpx;
          height: 60rpx;
        }
      }
    }
  }
}
</style>
